﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using Newtonsoft.Json;

namespace Fa.Kanbox.API.Demo
{
    public class MyGlobal
    {
        private static FLogin _FLogin = null;
        public static FLogin FLogin
        {
            get
            {
                if (_FLogin == null)
                    _FLogin = new FLogin();
                return _FLogin;
            }
        }
        private static FMain _FMain = null;

        public static FMain FMain
        {
            get
            {
                if (_FMain == null)
                    _FMain = new FMain();
                return _FMain;
            }
        }
        private static KbApiClient _ApiClient = null;
        public static KbApiClient ApiClient
        {
            get
            {
                if (_ApiClient == null)
                    _ApiClient = new KbApiClient(System.Configuration.ConfigurationManager.AppSettings["client_id"], System.Configuration.ConfigurationManager.AppSettings["client_secret"]);
                return _ApiClient;
            }
        }
        private static List<KbTokenInfo> _TokenInfos = new List<KbTokenInfo>();

        public static List<KbTokenInfo> TokenInfos
        {
            get
            {
                return _TokenInfos;
            }
        }
        private const string TokenFileName = "token.db";

        public static void LoadTokenInfos()
        {
            var filePath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, TokenFileName);
            TokenInfos.Clear();
            if (File.Exists(filePath))
            {
                var infos = JsonConvert.DeserializeObject<KbTokenInfo[]>(File.ReadAllText(filePath));
                TokenInfos.AddRange(infos);
            }
        }

        public static void WriteTokenInfos()
        {
            var filePath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, TokenFileName);
            var str = JsonConvert.SerializeObject(TokenInfos);
            using (var sw = new StreamWriter(filePath, false))
            {
                sw.Write(str);
            }
        }
    }
}
